package wwl.lsf.hellospringboot.test.nio.nio入门;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.SortedMap;

public class NioServer {

  public static void main(String[] args) throws Exception {

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

    Selector selector = Selector.open();

    ServerSocketChannel bind = serverSocketChannel.bind(new InetSocketAddress(9999));

    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {

      if (selector.select(5000) == 0) {
        System.out.println("没有客户端搭理我,我就干别的事");
        continue;
      }

      Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

      while (iterator.hasNext()) {
        SelectionKey key = iterator.next();

        if (key.isAcceptable()) {
          System.out.println("客户端是连接请求");
          SocketChannel socketChannel = serverSocketChannel.accept();
          socketChannel.configureBlocking(false);
//          socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
        }

        if (key.isReadable()) {
          SocketChannel channel = (SocketChannel) key.channel();
          ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
          channel.read(byteBuffer);
          System.out.println("客户端发来的数据:"+new String(byteBuffer.array()));

        }

        iterator.remove();
      }

    }


  }

}
